# coding:utf-8
# 星融元
import paramiko
import re
from os import devnull
from network.base_connection import BaseConnection
from network.CustomizedException import *
paramiko.util.log_to_file(devnull, level=paramiko.common.WARNING)


class Asterfusion(BaseConnection):

    """创建和销毁ssh会话"""

    def _set_pagination_param(self):
        """
        设置设备分页相关的默认参数，若用户指定了相关参数，则优先使用用户设置的参数
        分页标识符仅在每次从缓冲区读取的命令回显的最后一行中查找
        """
        if not self.no_pagination_cmd:
            self.no_pagination_cmd = ""     # 未找到命令
        if self.logger:
            self.logger.debug(f"no_pagination_cmd:`{self.no_pagination_cmd}`")
        if not self.pagination_pattern:
            self.pagination_pattern = re.compile(r"byte \d+")
        if self.logger:
            self.logger.debug(f"pagination_pattern:`{self.pagination_pattern}`")
        if not self.next_page_cmd:
            self.next_page_cmd = " "
        if self.logger:
            self.logger.debug(f"next_page_cmd:`{self.next_page_cmd}`")

    def _set_prompt_patterns(self):
        """
        设置已知的命令提示符正则模式元组
        命令提示符仅在每次从缓冲区读取的命令回显的最后一行中查找
        """
        patterns = {
            re.compile(r"^\S+#\s*$"),
            re.compile(r"[y/N]:\s*$", flags=re.I),
        }
        if self.pagination_pattern:
            patterns.add(self.pagination_pattern)
        if self.prompt_patterns:
            patterns.update(self.prompt_patterns)
        self.prompt_patterns = patterns
        if self.logger:
            self.logger.debug(f"prompt_patterns:{self.prompt_patterns}")

    def _set_error_patterns(self):
        """
        设置已知的命令错误提示正则模式元组
        错误提示符会在命令回显的每行中查找，所以需要修饰符re.M
        """
        patterns = {
            re.compile(r"^Syntax error:", flags=re.M),
        }
        if self.error_patterns:
            patterns.update(self.error_patterns)
        self.error_patterns = patterns
        if self.logger:
            self.logger.debug(f"error_patterns:{self.error_patterns}")

    """视图切换"""

    def change_mode(self, mode):
        """
        更改命令模式
        :param str mode:命令模式，可选参数：user|enable|config
        user    用户视图
        enable  特权视图
        config  全局配置视图
        """
        if mode == "user":
            msg = "Asterfusion dose not support mode `user`, the valid mode is `enable` or `config`"
            if self.logger:
                self.logger.warning(msg)
            raise UnSupportedException(msg)
        elif mode == "enable":
            self.shell("end")
            if self.logger:
                self.logger.info(f"change mode to {mode}")
        elif mode == "config":
            self.shell("end")
            self.shell("configure terminal")
            if self.logger:
                self.logger.info(f"change mode to {mode}")
        else:
            msg = "unknown mode `{}`, the valid mode is `user`, `enable` or `config`".format(mode)
            if self.logger:
                self.logger.warning(msg)
            raise UnSupportedException(msg)

    """读写channel"""

    def shell_search_set(self, cmds, ignore=False, loop_delay=0.5, strict=False, cmd_error=True):
        """
        执行一组查询命令并进行结果检查，若任一命令错误则抛出异常，否则返回一组结果命令回显
        :param [str] cmds:要执行的命令集合
        :param bool ignore: 是否忽略错误
            True    当前命令出错不会影响下一条命令的执行
            False   当前命令出错，终止剩余命令的执行
        :param float loop_delay: 延迟时间
        :param bool strict: 是否严格执行命令提示符匹配
            True    无法匹配命令提示符时引发超时异常
            False   无法匹配命令提示符时仍会返回结果
        :param bool cmd_error: 是否对命令结果进行异常检查
        """
        if self.logger:
            self.logger.info(f"try to execute a set of search commands with param:ignore={ignore}, loop_delay={loop_delay}, strict={strict}, cmd_error={cmd_error}.\ncommands:{cmds}")
        self.change_mode("enable")
        while cmds:
            cmd = cmds.pop(0)
            try:
                res = self.shell(cmd=cmd, loop_delay=loop_delay, strict=strict, cmd_error=cmd_error)
                yield {"state": True, "res": res, "message": ""}
            except Exception as e:
                yield {"state": False, "res": "", "message": repr(e)}
                if not ignore:
                    if self.logger:
                        self.logger.error(f"error occur while execute command `{cmd}`, terminates execution of the command set")
                    break
        if self.logger:
            self.logger.info("search command set execute finish")

    def shell_config_set(self, cmds, loop_delay=0.5, strict=False, cmd_error=True):
        """
        执行一组查询命令并进行结果检查，若任一命令错误则抛出异常
        :param [str] cmds:要执行的命令集合
        :param float loop_delay: 延迟时间
        :param bool strict: 是否严格执行命令提示符匹配
            True    无法匹配命令提示符时引发超时异常
            False   无法匹配命令提示符时仍会返回结果
        :param bool cmd_error: 是否对命令结果进行异常检查
        """
        if self.logger:
            self.logger.info(f"try to execute a set of config commands with param:loop_delay={loop_delay}, strict={strict}, cmd_error={cmd_error}.\ncommands:{cmds}")
        self.change_mode("config")
        while cmds:
            cmd = cmds.pop(0)
            try:
                res = self.shell(cmd=cmd, loop_delay=loop_delay, strict=strict, cmd_error=cmd_error)
                yield {"state": True, "res": res, "message": ""}
            except Exception as e:
                yield {"state": False, "res": "", "message": repr(e)}
                if self.logger:
                    self.logger.error(f"error occur while execute command `{cmd}`, terminates execution of the command set")
                break
        if self.logger:
            self.logger.info("config command set execute finish")

    """配置保存"""

    def save(self):
        """保存配置"""
        try:
            self.shell("write")
            if self.logger:
                self.logger.info("save configuration success")
        except Exception as e:
            if self.logger:
                self.logger.error(f"save configuration failure:{str(e)}")
            raise ConfigSaveException(str(e))

    """扩展功能"""

    def platform(self):
        """
        获取设备平台(操作系统)类型, 获取不到则返回None
        目前已支持类型：NX-OS、IOS
        """
        # 获取平台类型（操作系统类型）
        if not hasattr(self, "__platform"):
            self.__platform = None
            self.change_mode("enable")
            res = self.shell("show version brief")
            patterns = [
                re.compile(r"^HwSKU:\s*(\S+)", re.M),
            ]
            for pattern in patterns:
                platform = pattern.findall(res)
                if platform:
                    self.__platform = platform[0]
                    break
        if self.logger:
            self.logger.debug(f"return __platform: {self.__platform}")
        return self.__platform


